﻿using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Collections.Generic;
using KLY.DataModels;
using System.Linq;

namespace KLY.Tools.Helper
{
    public static class HttpAgent
    {

        #region Api

        /// <summary>
        /// 发送一个httpWebRequest并返回字符串
        /// </summary>
        /// <param name="url">请求的Url<</param>
        /// <param name="postData">Post的内容</param>
        /// <param name="listHeader">Header中需要增加的内容</param>
        /// <returns></returns>
        public static string SendHttpPost(string url, string postData, List<RequestHead> listHeader = null)
        {
            HttpWebRequest request;
            request = (HttpWebRequest)WebRequest.Create(url);
            if (listHeader != null && listHeader.Any())
            {
                foreach(var item in listHeader)
                {
                    request.Headers.Add(item.HeaderName, item.HeaderValue);
                }
            }
            request.Timeout = 5000;
            request.Method = "POST";
            Stream requestStream = request.GetRequestStream();
            StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.Default);
            streamWriter.Write(postData);
            streamWriter.Close();

            string result = string.Empty;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                if(response.StatusCode != HttpStatusCode.OK)
                {
                    return result;
                }

                using(Stream streamResponse = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(streamResponse);
                    result = reader.ReadToEnd();
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteLogError(string.Format("HttpAgent(字符串)请求发生异常\r\n{0}\r\n uri={1}\r\n postData={2}", ex, url, postData));
            }
            return result;
        }

        public static T SendHttpPost<T>(string url, string postData, List<RequestHead> listHeader = null)
            where T:class
        {
            string result;
            T resultData;

            result = string.Empty;
            resultData = null;

            try
            {
                result = SendHttpPost(url, postData, listHeader);
                if (string.IsNullOrWhiteSpace(result))
                {
                    resultData = null;
                }
                else
                {
                    resultData = JsonHelper.DeSerialize<T>(result);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError(string.Format("HttpAgent(字符串)请求发生异常\r\n{0}\r\n uri={1}\r\n postData={2}", ex, url, postData));
            }
            return resultData;
        }

        public static string SendHttpGet(string url, List<RequestHead> listHeader = null)
        {
            HttpWebRequest request;
            request = (HttpWebRequest)WebRequest.Create(url);
            if (listHeader != null && listHeader.Any())
            {
                foreach (var item in listHeader)
                {
                    request.Headers.Add(item.HeaderName, item.HeaderValue);
                }
            }
            request.Timeout = 5000;
            request.Method = "GET";
            string result = string.Empty;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return result;
                }

                using (Stream streamResponse = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(streamResponse);
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError(string.Format("HttpAgent(字符串)请求发生异常\r\n{0}\r\n uri={1}", ex, url), ex);
            }
            return result;
        }

        public static T SendHttpGet<T>(string url, List<RequestHead> listHeader = null)
            where T:class
        {
            string result;
            T resultData;

            result = string.Empty;
            resultData = null;

            try
            {
                result = SendHttpGet(url, listHeader);
                if(string.IsNullOrWhiteSpace(result))
                {
                    resultData = null;
                }
                else
                {
                    resultData = JsonHelper.DeSerialize<T>(result);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLogError(string.Format("HttpAgent(字符串)请求发生异常\r\n{0}\r\n uri={1}", ex, url), ex);
            }
            return resultData;
        }

        #endregion
    }
}
